#传送文件
# 服务器端：

import socket,os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 9000))
s.listen()
conut = 0
while 1:
    conn, addr = s.accept()
    conut += 1
    print(f'[{conut}] got a new connection:[{addr}]')
    while 1:
        #     1.接收客户端指令   解析指令动作
        cmd = conn.recv(1024).decode()
        if not cmd:
            print(f'与[{addr}]连接断开')
            break
        print(f'from client [{addr}]:{cmd}')
        if cmd.startswith('get'):
        # 2.查找文件是否存在   如果存在就传送
            file_name = cmd.split()[1]
            if os.path.isfile(file_name):
          #     3.传送文件大小的固定消息头
                file_size = os.path.getsize(file_name)
                mag_head = f'|{file_size}'.zfill(32)
                conn.send(mag_head.encode())
            #     4.打开文件，传送文件  ，内容
                f = open(file_name, 'rb')
                for i in f:
                    conn.send(i)
                f.close()
                print(f'file {file_name} has send , size:{file_size}')
            else:
                pass

s.close()



































